package dai.samples.reporters;

import com.codahale.metrics.*;
import dai.samples.metrics.GaugesTest;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author daify
 * @date 2022-05-09
 */
public class FilterReporters {

    private static Queue<String> queue = new LinkedList<String>();

    private static Counter counter;

    private static Random random = new Random();


    public static void main(String[] args) throws InterruptedException, IOException {
        // 创建一个度量
        MetricRegistry registry = new MetricRegistry();
        // 注册到控制台中
        ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
                .filter((name, metric) -> Objects.equals(MetricRegistry.name(GaugesTest.class, "queue", "size"),name))
                .build();
        // 每5秒输出一次结果
        reporter.start(5, TimeUnit.SECONDS);
        Gauge gauge = () -> queue.size();
        // 注册统计内容
        registry.register(MetricRegistry.name(GaugesTest.class, "queue", "size"),gauge);
        counter = registry.counter(MetricRegistry.name(Queue.class,"jobs","size"));


        int num = 1;
        while(true){
            Thread.sleep(200);
            if (random.nextDouble() > 0.7){
                String job = takeJob();
            }else{
                String job = "Job-"+num;
                addJob(job);
            }
            num++;
        }
    }

    private static void addJob(String job) {
        counter.inc();
        queue.offer(job);
    }

    private static String takeJob() {
        counter.dec();
        return queue.poll();
    }


}
